package com.unicorn.auth.web.controller;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.unicorn.auth.domain.User;
import com.unicorn.auth.domain.UserValidator;
import com.unicorn.auth.web.extension.util.NativeWebUtil;
import com.unicorn.auth.web.listener.WebSessionListener;


@Controller
public class LoginController {
	private final static Logger log =  LoggerFactory.getLogger(LoginController.class);
	private UserValidator validator = new UserValidator();
	public final static String SESSION_KEY  =  "USER";
	public final static String SESSION_IP  =  "IP";
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(HttpServletRequest request,@ModelAttribute("user") User user,Errors errors){
		if(!loginable(user.getLoginName(), NativeWebUtil.getClientIP(request))){
			return "error";
		}
		log.debug(user.toString());
		validator.validate(user, errors);
		if(errors.hasErrors()){
			log.error("未通过参数验证:{}",errors);
			return "login";
		}
		request.getSession().setAttribute(SESSION_KEY, user);
		request.getSession().setAttribute(SESSION_IP, NativeWebUtil.getClientIP(request));
		return "main";
	}
	@RequestMapping(value={"/login","/"},method=RequestMethod.GET)
	public String toLogin(HttpServletRequest request){
		return "login";
	}

	public boolean loginable(String loginName,String clientIP) {
		boolean flag = true;
		Map<String, HttpSession> sessionMap = WebSessionListener.getSessionMap();
		Set<String> keyset = sessionMap.keySet();
		for(Iterator<String> it = keyset.iterator();it.hasNext();){
			String id = it.next();
			HttpSession session = sessionMap.get(id);
			User user = (User)session.getAttribute(SESSION_KEY);
			if(user==null)
				continue;
			String sessionUserString = user.getLoginName();
			String ip = (String)session.getAttribute(SESSION_IP);
			if(!(StringUtils.hasText(ip)&&StringUtils.hasText(ip)))
				continue;
			if(loginName.equals(sessionUserString)&&!clientIP.equals(ip)){
				flag = false;
				break;
			}
		}
		return flag;
		
	}
}
